# view.py

import tkinter as tk
from tkinter import messagebox

class SqlQueryView:
    def __init__(self, controller):
        self.controller = controller
        self.root = tk.Tk()
        self.root.title("SQL Query Builder")

        # 表名输入
        tk.Label(self.root, text="表名:").grid(row=0, column=0, padx=5, pady=5)
        self.table_name_entry = tk.Entry(self.root)
        self.table_name_entry.grid(row=0, column=1, padx=5, pady=5)

        # 查询条件输入
        tk.Label(self.root, text="查询条件:").grid(row=1, column=0, padx=5, pady=5)
        self.condition_keys_entries = []
        self.condition_values_entries = []
        for i in range(3):  # 假设最多支持3个条件
            tk.Label(self.root, text=f"键{i+1}:").grid(row=2+i, column=0, padx=5, pady=5)
            key_entry = tk.Entry(self.root)
            key_entry.grid(row=2+i, column=1, padx=5, pady=5)
            self.condition_keys_entries.append(key_entry)

            tk.Label(self.root, text=f"值{i+1}:").grid(row=2+i, column=2, padx=5, pady=5)
            value_entry = tk.Entry(self.root)
            value_entry.grid(row=2+i, column=3, padx=5, pady=5)
            self.condition_values_entries.append(value_entry)

        # 字段输入
        tk.Label(self.root, text="字段:").grid(row=5, column=0, padx=5, pady=5)
        self.fields_entries = []
        for i in range(5):  # 假设最多支持5个字段
            field_entry = tk.Entry(self.root)
            field_entry.grid(row=6+i, column=1, padx=5, pady=5)
            self.fields_entries.append(field_entry)

        # 生成 SQL 按钮
        generate_button = tk.Button(self.root, text="生成 SQL", command=self.generate_sql)
        generate_button.grid(row=11, column=0, columnspan=2, padx=5, pady=5)

        # 保存 SQL 按钮
        save_button = tk.Button(self.root, text="保存 SQL", command=self.save_sql)
        save_button.grid(row=11, column=2, columnspan=2, padx=5, pady=5)

        # 结果显示
        tk.Label(self.root, text="生成的 SQL 语句:").grid(row=12, column=0, padx=5, pady=5)
        self.result_text = tk.Text(self.root, height=10, width=80)
        self.result_text.grid(row=13, column=0, columnspan=4, padx=5, pady=5)

    def generate_sql(self):
        tbl = self.table_name_entry.get()
        cons = {key_entry.get(): value_entry.get() for key_entry, value_entry in zip(self.condition_keys_entries, self.condition_values_entries) if key_entry.get() and value_entry.get()}
        fields = [field_entry.get() for field_entry in self.fields_entries if field_entry.get()]
        sql_query = self.controller.generate_sql(tbl, cons, fields)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, sql_query)

    def save_sql(self):
        sql_query = self.result_text.get(1.0, tk.END).strip()
        if not sql_query:
            messagebox.showwarning("警告", "没有生成的 SQL 语句")
            return
        self.controller.save_sql(sql_query)

    def run(self):
        self.root.mainloop()